<?php
/**
 * 轮播
 * Author: 毛康燕
 * Date: 2021/6/16
 */

namespace app\backend\controller\v1;

use app\backend\validate\BannerValidate;
use app\BaseController;
use app\common\model\Banner as BannerModel;
use think\exception\ValidateException;
use think\facade\Filesystem;

class Banner extends BaseController
{

    //显示
    public function index()
    {
        $model = new BannerModel();
        $page = input('page/d', 1);
        $title = input('title');
        $where = [];
        if (!empty($title)) {
            $where[] = [
                ['title', 'like', "%$title%"],
            ];
        }
        $ban = $model
            ->where($where)
            ->page($page, 5)
            ->select();
        $count = $model
            ->where($where)
            ->count();
        $maxpage = ceil($count / 5);
        return sucessMsg(200, '获取成功！', ['ban' => $ban, 'maxpage' => $maxpage]);
    }

    //添加
    public function create()
    {
        $user = new BannerModel();
        $data = input();
        $data['image'] = delYuming($data['image']);
        try {
            validate(BannerValidate::class)->scene('create')->check($data);
            if ($user->save($data)) {
                return sucessMsg(200, '创建成功！', $user->id);
            }
            return errMsg(500, '创建失败！');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    //修改
    public function update()
    {
        $id = input('id/d');
        if (empty($id)) {
            return errMsg(400, '请选择id');
        }
        $user = BannerModel::find($id);
        $data = input();
        $data['image'] = delYuming($data['image']);
        try {
            if (BannerModel::update($data, ['id' => $id])) {
                return sucessMsg(200, '修改成功！', $id);
            }
            return errMsg(500, '修改失败！');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    //删除
    public function delete()
    {
        $data = input();
        $model = BannerModel::destroy($data['id']);
        if ($model) {
            return sucessMsg(200, '删除成功！');
        } else {
            return errMsg(500, '删除失败！');
        }
    }

    //图片上传
    public function uploads_file()
    {
        if (!request()->file()) {
            return errMsg(500, '未上传图片！');
        }
        $file = request()->file('file');
        if (empty($file)) {
            return errMsg(500, '未上传图片！');
        }
        $temp = explode(".", $_FILES["file"]["name"]);
        $extension = end($temp);

        if (!in_array($extension, array("jpeg", "jpg", "png"))) {
            return errMsg(500, '上传图片不合法！');
        }
        $saveName = Filesystem::disk('public')->putFile('uploads', $file);
        $phonto_name = env('DATABASE.YUMING') . str_replace('\\', '/', $saveName);
        return sucessMsg(200, '上传成功！', $phonto_name);
    }
}